//
//  CHSimpleListView.swift
//  CHSimpleUI
//
//  Created by cyptt on 2023/3/31.
//

import UIKit

public class CHSimpleListView: UIView,UITableViewDelegate  {

    private let CELLID = "CHSimpleListCellID"
    private var tabDataSource:CHSimpleListDataSource?
    private var viewModel:CHSimpleListViewModel?
    
    private var clickItemCallBack:((_ index:Int,_ simpleModel:CHSimpleListModel?) -> ())?
    
    private var inputResultCallBack:((_ textResult:String,_ index:Int,_ simpleModel:CHSimpleListModel?) -> ())?
    
   

    public override func awakeFromNib() {
        super.awakeFromNib()
        self.setUI()
    }
    public override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUI()
   
    }
    
    public init(){
        super.init(frame: .zero)
        self.setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public var spaceTabHeaderH:CGFloat = 0 //占位头高度
    public var spaceTabFootH:CGFloat = 0 //占位底部高度
    
   
    deinit{
       print("CHSimpleListView--deinit")
    }
    private func setUI(){
        
        weak var weakSelf = self
        self.tabDataSource = CHSimpleListDataSource(identifier: CELLID,successCallBack: { cell, model, indexPath, tableView in
            let model:CHSimpleListModel? = model as? CHSimpleListModel
            
            let cell:CHSimpleListCell? = cell as? CHSimpleListCell
            cell?.backgroundColor = weakSelf?.backgroundColor
          
         
          
            if model?.leftTitle != nil{
                cell?.leftL.text = model?.leftTitle
            }
            if model?.centerTitle != nil{
                cell?.centerL.text = model?.centerTitle
            }
            if model?.rightTitle != nil{
                cell?.rightL.text = model?.rightTitle
            }
            
            if model?.leftImage != nil{
                cell?.leftImageV.image = model?.leftImage
            }
         
            if model?.rightImage != nil {
                cell?.rightImageV.image = model?.rightImage
            }

            if model?.cellHandelr != nil {
                model?.cellHandelr!(cell)
            }
            
            if model?.lineLeftW != nil{
                cell?.lineLeftCons?.update(offset: (model!.lineLeftW))
            }else{
                cell?.lineLeftCons?.update(offset: (0))
            }
            if model?.lineRightW != nil{
                cell?.lineRightCons?.update(offset:-model!.lineRightW)
            }else{
                cell?.lineRightCons?.update(offset:0)
            }
     
       
            if model?.lineIsRight == true{
                cell?.lineViewRightV.isHidden = false
            }else{
                cell?.lineViewRightV.isHidden = true
            }
            
            if model?.rightImage2 != nil{
                cell?.rightImageView2.image = model?.rightImage2
            }else{
                cell?.rightImageView2.image = UIImage.init(named: "")
            }
            
            if model?.cellType == .L_Title_R_IMG_IMG{
               
                cell?.rightImageV2WCons?.update(offset:model!.rightImage2W)
                cell?.rightImageV2HCons?.update(offset: model!.rightImage2H)
            }
            
            cell?.cellInputResultCallBack(clouse: { textResult in
                if weakSelf?.inputResultCallBack != nil{
                    weakSelf?.inputResultCallBack!(textResult,indexPath.row,model)
                }
            })
            
          
        })
        
        self.viewModel = CHSimpleListViewModel.init(successBlock: { vModelResult in
            
            weakSelf?.tabDataSource?.datas = vModelResult as! [Any]
            weakSelf?.tableView.reloadData()
        },failBlock: { vModelFailMsg in
            
        })
    }
    /*
     确定回调
     */

    public func cellItemClickCallBack(clouse:@escaping(_ index:Int,_ simpleModel:CHSimpleListModel?)-> Void){
        self.clickItemCallBack = clouse
    }
    
    /*
     input 输入完回调
     */
    public func cellInputResultCallBack(clouse:@escaping(_ textResult:String, _ index:Int,_ simpleModel:CHSimpleListModel?)-> Void){
        self.inputResultCallBack = clouse
    }
    /*
     设置数据源
     */
    public func setDataSource(listModels:[CHSimpleListModel]){

     
        self.viewModel?.datas = listModels
        self.viewModel?.refreshData()
    }
    
    /*
     @index 从0开始
     @ isChangeSyle 是否改变样式 ，默认不改变
     刷新某一条数据
     
     */
    public func freshItem(index:Int,listModel:CHSimpleListModel,isChangeSyle:Bool = false){
        
        if self.viewModel?.datas == nil || self.viewModel == nil {
            return
        }
        
        var newDatas:[CHSimpleListModel] = []
        for i in 0..<self.viewModel!.datas.count{
            var item  = self.viewModel!.datas[i] as! CHSimpleListModel
            if i == index{
                if isChangeSyle == true{
                    item = listModel
                }else{
//                    item.cellType = item.cellType
//                    item.cellHandelr = item.cellHandelr
                    item.leftTitle = listModel.leftTitle
                    item.rightTitle = listModel.rightTitle
                    item.centerTitle = listModel.centerTitle
                    item.rightImage = listModel.rightImage
                    item.leftImage = listModel.leftImage
                    item.cellHigh = listModel.cellHigh
                    item.lineLeftW = listModel.lineLeftW
                    item.lineRightW = listModel.lineRightW
                    item.rightImage2 = listModel.rightImage2
                    item.rightImage2H = listModel.rightImage2H
                    item.rightImage2W = listModel.rightImage2W
                }
            
            }
            newDatas.append(item )
        }
      
        self.viewModel?.datas = newDatas
      
        self.viewModel?.refreshData()
    }
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        self.addSubview(self.tableView)
        
        if self.spaceTabHeaderH != 0 {
            self.tableView.tableHeaderView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.spaceTabHeaderH))
        }

        if self.spaceTabFootH != 0 {
            self.tableView.tableFooterView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.spaceTabFootH))
        }
        self.tableView.snp.makeConstraints { make in
            make.width.height.equalToSuperview()
            make.center.equalToSuperview()
        }
        
    }
    
 
 
    
  public  lazy var tableView = {()-> UITableView in
        let tabV = UITableView.init();
        tabV.delegate = self;
        tabV.dataSource = self.tabDataSource;
        tabV.backgroundColor = UIColor.clear
        tabV.separatorColor = UIColor.clear
        return tabV;
    }()
    
    
}


extension CHSimpleListView{
   
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model:CHSimpleListModel? = self.tabDataSource?.datas[indexPath.row] as? CHSimpleListModel
        return model?.cellHigh ?? 50
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        let model:CHSimpleListModel? = self.tabDataSource?.datas[indexPath.row] as? CHSimpleListModel
        if self.clickItemCallBack != nil{
            self.clickItemCallBack!(indexPath.row,model)
        }
    }
}
